package com.yan.club.sys.service.impl;

import com.yan.club.exception.ServiceException;
import com.yan.club.result.Result;
import com.yan.club.sys.mapper.SysCommunityMapper;
import com.yan.club.sys.mapper.SysRoleMapper;
import com.yan.club.sys.model.SysCommunity;
import com.yan.club.sys.model.SysCommunityExample;
import com.yan.club.sys.model.SysRole;
import com.yan.club.sys.service.SysCommunityService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.yan.club.auth.utils.SecurityUtil.*;

/**
 * @author 彦
 * @since 2024/2/6 22:17
 */
@Service
public class SysCommunityServiceImpl implements SysCommunityService {

    @Resource
    private SysCommunityMapper deptMapper;

    @Resource
    private SysRoleMapper roleMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    public List<SysCommunity> selectDeptList(SysCommunity dept) {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysCommunity dept) {
        long deptId = dept.getDeptId() == null ? -1L : dept.getDeptId();

        // 名字 和 父级 不能相同
        SysCommunityExample ex = new SysCommunityExample();
        ex.createCriteria().andDeptNameEqualTo(dept.getDeptName())
                .andParentIdEqualTo(dept.getParentId())
                .andDelFlagEqualTo("0");

        List<SysCommunity> sysCommunities = deptMapper.selectByExample(ex);

        return !CollectionUtils.isEmpty(sysCommunities) && sysCommunities.get(0).getDeptId() != deptId;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId) {

        if (!isAdmin(getUserId())) {
            SysCommunity dept = new SysCommunity();
            dept.setDeptId(deptId);
            List<SysCommunity> depts = selectDeptList(dept);
            if (CollectionUtils.isEmpty(depts)) {
                throw new ServiceException("没有权限访问社团数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public Result<String> insertDept(SysCommunity dept) {
        SysCommunity info = deptMapper.selectByPrimaryKey(dept.getParentId());

        // 如果父节点不为正常状态,则不允许新增子节点
        if (!"0".equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }

        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        dept.setCreateTime(new Date());
        dept.setUpdateTime(new Date());
        dept.setCreateBy(getUser().getUserName());

        dept.setDelFlag("0");
        deptMapper.insert(dept);
        return Result.success();
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }


    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public Result<String> updateDept(SysCommunity dept) {
        SysCommunity newParentDept = deptMapper.selectByPrimaryKey(dept.getParentId());
        SysCommunity oldDept = deptMapper.selectByPrimaryKey(dept.getDeptId());
        if (!ObjectUtils.isEmpty(newParentDept) && !ObjectUtils.isEmpty(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }

        dept.setDelFlag("0");
        dept.setCreateBy(getUser().getUserName());
        dept.setUpdateBy(getUser().getUserName());
        dept.setCreateTime(new Date());
        dept.setUpdateTime(new Date());

        deptMapper.updateByPrimaryKey(dept);
        if ("0".equals(dept.getStatus()) && !StringUtils.isEmpty(dept.getAncestors())
                && !"0".equals(dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return Result.success();
    }


    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysCommunity dept) {
        String[] ancestors = dept.getAncestors().split(",");
        Long[] deptIds = Arrays.stream(ancestors).map(Long::parseLong).toArray(Long[]::new);

        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysCommunity> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysCommunity child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysCommunity selectDeptById(Long deptId) {
        return deptMapper.selectByPrimaryKey(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public Result<String> deleteDeptById(Long deptId) {
        deptMapper.deleteDeptById(deptId);
        return Result.success();
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<SysCommunity> selectDeptTreeList(SysCommunity dept) {
        List<SysCommunity> depts = selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysCommunity> buildDeptTree(List<SysCommunity> depts) {
        List<SysCommunity> returnList = new ArrayList<>();
        List<Long> tempList = depts.stream().map(SysCommunity::getDeptId).collect(Collectors.toList());
        for (SysCommunity dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<SysCommunity> buildDeptTreeSelect(List<SysCommunity> depts) {
        return buildDeptTree(depts);
//        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectByPrimaryKey(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.getDeptCheckStrictly());
    }

    @Override
    public List<SysCommunity> listCategory(SysCommunity dept) {
        List<SysCommunity> sysCommunities = deptMapper.selectDeptList(dept);
        ArrayList<SysCommunity> list = new ArrayList<>();
        for (SysCommunity sysCommunity : sysCommunities) {
            String[] split = sysCommunity.getAncestors().split(",");
            if (split.length == 2) {
                list.add(sysCommunity);
            }
        }
        return list;
    }

    @Override
    public List<SysCommunity> listCommunity(SysCommunity dept) {
        List<SysCommunity> sysCommunities = deptMapper.selectDeptList(dept);
        ArrayList<SysCommunity> list = new ArrayList<>();
        for (SysCommunity sysCommunity : sysCommunities) {
            String[] split = sysCommunity.getAncestors().split(",");
            if (split.length == 3) {
                list.add(sysCommunity);
            }
        }
        return list;
    }


    /**
     * 递归列表
     */
    private void recursionFn(List<SysCommunity> list, SysCommunity t) {
        // 得到子节点列表
        List<SysCommunity> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysCommunity tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysCommunity> getChildList(List<SysCommunity> list, SysCommunity t) {
        List<SysCommunity> tlist = new ArrayList<>();
        for (SysCommunity n : list) {
            if (n.getParentId() != null && n.getParentId().equals(t.getDeptId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysCommunity> list, SysCommunity t) {
        return !getChildList(list, t).isEmpty();
    }

}
